﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;
using UCommonWork.Common;
using UEntity.LogEntity;

namespace RMSWebService
{
    /// <summary>
    /// RMSService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WaterMark : System.Web.Services.WebService
    {
    
        private ELogRecordEntity LogEntity = new ELogRecordEntity();

        private string strkey = Convert.ToString(ConfigurationManager.AppSettings["KeyGuid"]);
        private string strServerUrl = Convert.ToString(ConfigurationManager.AppSettings["ServerUrl"]);
        private string strEnableWaterMark = Convert.ToString(ConfigurationManager.AppSettings["EnableWaterMark"]);
        private string strRegFileType = Convert.ToString(ConfigurationManager.AppSettings["RegFileType"]);
        private string strRegWaterMarkType = Convert.ToString(ConfigurationManager.AppSettings["RegWaterMarkType"]);
        private string strLocalFilePath = Convert.ToString(ConfigurationManager.AppSettings["LocalFilePath"]);
        private static Uri rmsUrl = new Uri(ConfigurationManager.AppSettings["RmsUrl"]);


        //private void RecordLog()
        //{
        //    LogEntity.Operator = "RMSWebService";
        //    LogEntity.OperateIP = "10.127.127.1";
        //    ULogWork.CLogToDataBase.RecordOperateLog(LogEntity);
        //}
        /// <summary>
        /// 对文件添加水印
        /// </summary>
        /// <param name="strCurrentTime">时间</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="fileBuffer">上传文件的字节流</param>
        /// <returns>成功“1&空字符串”失败“0&失败原因”</returns>
        [WebMethod]
        public string MarkFile(string key,string strCurrentTime, string fileName, string setWarterMark, string strWatertMark, byte[] buffer)
        {
            
            string strResult = "1&";
            string strError = string.Empty;
            string strWebError = string.Empty;
            bool bResult = true;
            this.LogEntity.OperateTime = DateTime.Now;
            this.LogEntity.Module = "EncryptFile";
            this.LogEntity.OperateObject = "水印文件";
            this.LogEntity.OperateResult = "Loading";
            this.LogEntity.OperationDescription = string.Format("Function:key:{0},strCurrentTime:{1},fileName:{2},setWarterMark:{3},strWatertMark:{4}", new object[]
              {
                key,
                strCurrentTime,
                fileName,
                setWarterMark,
                strWatertMark
            });
            this.RecordLog();
            try
            {
                bool flag = string.IsNullOrEmpty(strCurrentTime) || string.IsNullOrEmpty(fileName) || buffer == null;
                if (flag)
                {
                    strWebError = "请检查参数是否齐全";
                    strError = strWebError;
                    bResult = false;
                }
                else
                {
                    fileName = System.Web.HttpUtility.UrlDecode(fileName);

                    //特殊符号+号需要剔除掉，会影响IIS解析
                    fileName = fileName.Replace("+", "");
                    //todo
                    bool flag2 = !Commons.IsOverTime(strCurrentTime);
                    if (flag2)
                    {
                        strError = "访问超时";
                        strWebError = "访问超时";
                        bResult = false;
                    }
                    else
                    {
                        //todo
                        bool flag3 = md5(string.Format("{0};{1}", this.strkey, strCurrentTime)) != key;
                        if (flag3)
                        {
                            strError = "密钥不正确";
                            strWebError = "密钥不正确";
                            bResult = false;
                        }
                        else
                        {
                            Regex regex = new Regex(this.strRegFileType);
                            bool flag4 = !regex.Match(fileName.ToLower()).Success;
                            if (flag4)
                            {
                                strError = "不支持该文件格式！";
                                strWebError = "不支持该文件格式！";
                                bResult = false;
                            }
                            else
                            {
                                string ServerPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

                                IOExtension.MakeDir(true, $@"{ServerPath}\WaterMark\");

                                string Upload = $@"{ServerPath}\WaterMark\";

                                if (!Directory.Exists(Upload))
                                {
                                    Directory.CreateDirectory(Upload);
                                }
                                string tempPath = Upload + Path.GetFileName(Path.GetFileNameWithoutExtension(fileName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + Path.GetExtension(fileName));
                                FileStream fs = new FileStream(tempPath, FileMode.Create);
                                BinaryWriter bw = new BinaryWriter(fs);
                                bw.Write(buffer);
                                bw.Close();
                                fs.Close();
                                Regex reg = new Regex(this.strRegWaterMarkType);
                                bool flag5 = setWarterMark == "1" && this.strEnableWaterMark == "1" && reg.Match(fileName.ToLower()).Success;
                                if (flag5)
                                {
                                    bool flag6 = string.IsNullOrEmpty(strWatertMark);
                                    if (flag6)
                                    {
                                        strWatertMark = " ";
                                    }
                                    bool flag7 = Path.GetExtension(fileName).IndexOf("doc") > -1;
                                    if (flag7)
                                    {
                                        bool flag8 = !WaterMarkProvider.WaterMarkWord(strWatertMark, tempPath, fileName, out strError);
                                        if (flag8)
                                        {
                                            strError = "水印内部异常:" + strError;
                                        }
                                    }
                                    bool flag9 = Path.GetExtension(fileName).IndexOf("xls") > -1;
                                    if (flag9)
                                    {
                                        bool flag10 = !WaterMarkProvider.WaterMarkExcel(strWatertMark, tempPath, fileName, out strError);
                                        if (flag10)
                                        {
                                            strError = "水印内部异常:" + strError;
                                        }
                                    }
                                    bool flag11 = Path.GetExtension(fileName).IndexOf("ppt") > -1;
                                    if (flag11)
                                    {
                                        bool flag12 = !WaterMarkProvider.WaterMarkPPT(strWatertMark, tempPath, fileName, out strError);
                                        if (flag12)
                                        {
                                            strError = "水印内部异常:" + strError;
                                        }
                                        bool flag13 = Path.GetExtension(fileName) == ".ppt";
                                        if (flag13)
                                        {
                                            tempPath += "x";
                                        }
                                    }
                                    bool flag14 = Path.GetExtension(fileName).IndexOf("pdf") > -1;
                                    if (flag14)
                                    {
                                        bool flag15 = !WaterMarkProvider.WaterMarkPDF(strWatertMark, tempPath, fileName, out strError);
                                        if (flag15)
                                        {
                                            strError = "水印内部异常:" + strError;
                                        }
                                    }
                                }
                                string filename = Path.GetFileName(tempPath).Replace("%", "%25");
                                filename = filename.Replace(" ", "%20");
                                filename = filename.Replace("#", "%23");
                                filename = filename.Replace("&", "%26");
                                filename = filename.Replace("(", "%28");
                                filename = filename.Replace(")", "%29");

                                filename = filename.Replace(",", "%2C");
                                filename = filename.Replace(";", "%3B");
                                filename = filename.Replace("=", "%3D");
                                filename = filename.Replace("@", "%40");
                                strResult = "1&" + this.strServerUrl + "/WaterMark/" + filename;
                                strResult = "1&" + this.strServerUrl + "download.aspx?" + this.strServerUrl + "/WaterMark/" + filename + "&file=" + fileName;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                strError = string.Format("EncryptFile Exception:{0}", ex.ToString());
                bool flag17 = strError.Contains("文件或目录损坏且无法读取");
                if (flag17)
                {
                    strWebError = "文件或目录损坏且无法读取";
                }
                else
                {
                    strWebError = "系统内部异常";
                }
                bResult = false;
            }
            bool flag18 = !bResult;
            if (flag18)
            {
                this.LogEntity.ErrorDescription = strError;
                this.LogEntity.OperateResult = "Fail";
                strResult = "0&" + strWebError;
            }
            else
            {
                this.LogEntity.OperateResult = "Success";
                this.LogEntity.ErrorDescription = strResult;
            }
            this.RecordLog();
            return strResult;
        }
        public string md5(string str)
        {
            try
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                byte[] bytValue = Encoding.UTF8.GetBytes(str);
                byte[] bytHash = md5.ComputeHash(bytValue);
                md5.Clear();
                string sTemp = "";
                for (int i = 0; i < bytHash.Length; i++)
                {
                    sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
                }
                str = sTemp.ToLower();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return str;
        }

        private void RecordLog()
        {
            LogEntity.Operator = "加解密程序";
            LogEntity.OperateIP = string.Empty;
            ULogWork.CLogToTxtFile.RecordOperateLog(LogEntity);
        }
    }
}
